package com.dituhui.tool.util;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

import org.apache.log4j.Logger;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;

import com.dituhui.tool.io.Constants;

/**
 * 定时任务工具。
 * 
 * @author liweigu
 * 
 */
public class TimedJob implements Job {
	protected static Logger LOGGER = Logger.getLogger(TimedJob.class);
	/**
	 * 调度表达式。如果值是null，则读取配置文件里"QuartzExpression"的值。
	 */
	public static String QuartzExpression = null;

	@Override
	/**
	 * 执行任务。可以重载此方法，实现需要在定时任务里执行的内容。
	 */
	public void execute(JobExecutionContext context) throws JobExecutionException {
		LOGGER.info("in TimedJob.execute(JobExecutionContext context).");
	}

	/**
	 * main方法
	 * 
	 * @param args args[0]传入job的class全名；args[1]值为"-r"时即时运行，否则定时执行。
	 */
	public static void main(String[] args) {
		try {
			if (args == null || args.length == 0) {
				System.out.println("Usage: args[0]传入job的class全名,args[1]为-r时即时执行");
			} else {
				String className = args[0];
				Class jobClass = Class.forName(className);
				TimedJob timedTask = (TimedJob) jobClass.newInstance();
				if (args.length > 1 && args[1].equals("-r")) {
					// 即时运行
					timedTask.execute(null);
				} else {
					// quatz调度表达式
					String expression = Constants.getValue("QuartzExpression");
					// quatz任务管理器
					TimedJobMagager expJobManager = new TimedJobMagager(expression, jobClass);
					// 添加任务
					expJobManager.addJob();
					// 启动调度器
					expJobManager.startScheduler();
				}
			}
		} catch (Exception e) {
			LOGGER.error("启动失败:" + e.getMessage());
		}
	}

	public static class TimedJobMagager {
		private SchedulerFactory schedulerFactory;
		private Scheduler sched;
		private CronTrigger trigger;
		private String JOB_GROUP_NAME = "ExportJobGroup";
		private String JOB_NAME = "ExportJob";
		private String TRIGGER_NAME = "ExportTrigger";
		private String TRIGGER_GROUP_NAME = "ExportTriggerGroup";
		public Class jobClass = null;

		/**
		 * 构造方法
		 * 
		 * @param triggerExpression 触发器表达式
		 * @throws SchedulerException
		 */
		public TimedJobMagager(String triggerExpression, Class jobClass) throws SchedulerException {
			this.jobClass = jobClass;
			this.schedulerFactory = new StdSchedulerFactory();
			// 获取调度器
			this.sched = schedulerFactory.getScheduler();
			// 创建触发器
			this.trigger = newTrigger().withIdentity(TRIGGER_NAME, TRIGGER_GROUP_NAME).withSchedule(cronSchedule(triggerExpression)).build();
			// trigger = newTrigger().withIdentity(TRIGGER_NAME,
			// TRIGGER_GROUP_NAME).withSchedule(cronSchedule("0/10 * * * * ?")).build();
		}

		/**
		 * 添加任务
		 * 
		 * @throws SchedulerException
		 */
		public void addJob() throws SchedulerException {
			if (this.jobClass == null) {
				LOGGER.warn("jobClass is null");
			} else {
				// 创建任务
				JobDetail jobDetail = newJob(this.jobClass).withIdentity(JOB_NAME, JOB_GROUP_NAME).build();

				// 将任务加入调度器
				this.sched.scheduleJob(jobDetail, this.trigger);
			}
		}

		/**
		 * 启动调度器
		 * 
		 * @throws SchedulerException
		 */
		public void startScheduler() throws SchedulerException {
			// 启动
			if (!sched.isShutdown()) {
				sched.start();
			}
		}
	}
}
